package com.scm.biz.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.scm.biz.bean.SysRole;
import com.scm.biz.bean.SysUser;
import com.scm.biz.bean.SysUserRole;
import com.scm.biz.dto.SysUserDto;
import com.scm.biz.dto.SysUserModifyDto;
import com.scm.biz.query.SysUserQuery;
import com.scm.biz.result.SysUserInfoResult;
import com.scm.biz.result.SysUserResult;
import com.scm.biz.service.SysRoleService;
import com.scm.biz.service.SysUserRoleService;
import com.scm.biz.service.SysUserService;
import com.scm.core.bean.exp.UfdmException;
import com.scm.core.bean.resp.RespBean;
import com.scm.utils.Const;
import com.scm.utils.EmailUtil;
import com.scm.utils.PropertiesUtil;
import com.scm.utils.UfdmMd5Util;

@Controller
@RequestMapping("/sysuser")
public class SysUserAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7935830951665903576L;
	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysRoleService sysRoleService;
	@Resource
	private SysUserRoleService sysUserRoleService;
	
	@RequestMapping("/list")
	//@LogConfig(operationModule=LogOperation.USER,description="用户查询")
	public ModelAndView list(Integer roleId,String name,Integer pageNo) throws Exception {
		SysUserQuery sysUserQuery = new SysUserQuery();
		sysUserQuery.setPageNo(pageNo);
		if(roleId==null||roleId==0){
			sysUserQuery.setRoleId(null);
		}else{
			sysUserQuery.setRoleId(roleId);
		}
		sysUserQuery.setName(name);
		ModelAndView mv = new ModelAndView("system/sys_user_list");
		List<SysUserDto> sysUserDtoList = new ArrayList<SysUserDto>();
		SysUserDto sysUserDto = null;
		for(SysUserResult sysUserResult:sysUserService.queryPage(sysUserQuery)){
			sysUserDto = new SysUserDto();
			sysUserDto.setId(sysUserResult.getId());
			sysUserDto.setEmail(sysUserResult.getEmail());
			sysUserDto.setStatus(sysUserResult.getStatus());
			sysUserDto.setName(sysUserResult.getName());
			sysUserDto.setMemo(sysUserResult.getMemo());
			sysUserDto.setSuperiorName(sysUserResult.getSuperior_name());
			//获取用户角色列表
			sysUserDto.setRoleList(sysRoleService.selectListByUserId(sysUserResult.getId()));
			sysUserDtoList.add(sysUserDto);
		}
		//获取所有角色
		mv.addObject("roleList", sysRoleService.selectList(null));
		mv.addObject("roleId", roleId);
		mv.addObject("name", name);
		mv.addObject("pageNo", pageNo);
		mv.addObject("sysUserList", sysUserDtoList);
		mv.addObject("splitPage", sysUserQuery.getSplitPage());
		return mv;
	}
	
	/**
	 * 获取编辑页的用户基本信息
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getEdit")
	@ResponseBody
	public RespBean<SysUserModifyDto> getEdit(String userId) throws Exception{
		RespBean<SysUserModifyDto> respBean = new RespBean<SysUserModifyDto>();
		int id = Integer.valueOf(userId);
		List<SysUserRole> userRoles = sysUserRoleService.selectListByUserId(id);
		List<SysRole> roles = sysRoleService.selectList(null);
		List<SysUser> users = sysUserService.queryList();
		SysUser user = sysUserService.selectByPrimaryKey(id);
		SysUserModifyDto sysUserModifyDto = new SysUserModifyDto();
		sysUserModifyDto.setUserRoles(userRoles);
		sysUserModifyDto.setRoles(roles);
		sysUserModifyDto.setUser(user);
		sysUserModifyDto.setUsers(users);
		respBean.setBody(sysUserModifyDto);
		return respBean;
	}
	@RequestMapping("/queryassign")
	@ResponseBody
	public RespBean<List<SysUser>> queryAssign() throws Exception{
		RespBean<List<SysUser>> respBean = new RespBean<List<SysUser>>();
		respBean.setBody(sysUserService.selectList());
		return respBean;
	}
	
	@RequestMapping("/getSave")
	@ResponseBody
	public RespBean<SysUserModifyDto> getSave() throws Exception{
		RespBean<SysUserModifyDto> respBean = new RespBean<SysUserModifyDto>();
		List<SysRole> roles = sysRoleService.selectList(null);
		List<SysUser> users = sysUserService.queryList();
		SysUserModifyDto sysUserModifyDto = new SysUserModifyDto();
		sysUserModifyDto.setRoles(roles);
		sysUserModifyDto.setUsers(users);
		respBean.setBody(sysUserModifyDto);
		return respBean;
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public RespBean<String> del(String userId) throws Exception {
		RespBean<String> respBean = new RespBean<String>();
		int id = Integer.valueOf(userId);
		sysUserService.delete(id);
		//删除该员工所有角色
		sysUserRoleService.deleteByUserId(id);
		respBean.setBody("删除成功");
		return respBean;
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public RespBean<String> save(SysUserDto sysUserDto) throws Exception {
		RespBean<String> respBean = new RespBean<String>();
		if(sysUserDto.getId()!=null){
			Integer id = sysUserDto.getId();
			//修改员工信息
			SysUser sysUser = new SysUser();
			if(sysUserDto.getEmail()==null||sysUserDto.getEmail().isEmpty()){
				throw new UfdmException("邮箱不能为空");
			}
			if(!sysUserDto.getEmail().matches(Const.EMAIL)){
				throw new UfdmException("邮箱规则不合法");
			}
			boolean res = sysUserService.haveEmail(sysUserDto.getEmail(), (long)sysUserDto.getId());
			if(res){
				throw new UfdmException("邮箱已注册");
			}
			if(sysUserDto.getName()==null||sysUserDto.getName().isEmpty()){
				throw new UfdmException("姓名不能为空");
			}
			if(sysUserDto.getRoles()==null||sysUserDto.getRoles().size()==0){
				throw new UfdmException("角色不能为空");
			}
			sysUser.setId(id);
			sysUser.setEmail(sysUserDto.getEmail());
			sysUser.setName(sysUserDto.getName());
			sysUser.setSuperior(sysUserDto.getSuperior());
			sysUser.setMemo(sysUserDto.getMemo());
			sysUser.setUpdatedAt(new Date());
			//修改上级领导和备注
			sysUserService.updateByPrimaryKeySelective(sysUser);
			//删除该员工所有角色
			sysUserRoleService.deleteByUserId(id);
			//插入修改后的所有角色
			for(Integer roleId : sysUserDto.getRoles()){
				SysUserRole sysUserRole = new SysUserRole();
				sysUserRole.setUserId(id);
				sysUserRole.setRoleId(roleId);
				sysUserRole.setCreateAt(new Date());
				sysUserRoleService.insert(sysUserRole);
			}
			respBean.setBody("用户修改成功");
			return respBean;
		}else{
			//新增员工
			SysUser sysUser = new SysUser();
			if(sysUserDto.getEmail()==null||sysUserDto.getEmail().isEmpty()){
				throw new UfdmException("邮箱不能为空");
			}
			if(!sysUserDto.getEmail().matches(Const.EMAIL)){
				throw new UfdmException("邮箱规则不合法");
			}
			boolean res = sysUserService.haveEmail(sysUserDto.getEmail(),null);
			if(res){
				throw new UfdmException("邮箱已注册");
			}
			if(sysUserDto.getName()==null||sysUserDto.getName().isEmpty()){
				throw new UfdmException("姓名不能为空");
			}
			if(sysUserDto.getRoles()==null||sysUserDto.getRoles().size()==0){
				throw new UfdmException("角色不能为空");
			}
			sysUser.setEmail(sysUserDto.getEmail());
			sysUser.setName(sysUserDto.getName());
			//获取6位随机密码
			String password = Const.getRandomPassword();
			/*sysUser.setPassword(UfdmMd5Util.MD5Encode(password));*/
			sysUser.setPassword(UfdmMd5Util.MD5Encode("111111"));
			sysUser.setSuperior(sysUserDto.getSuperior());
			sysUser.setMemo(sysUserDto.getMemo());
			sysUser.setCreatedAt(new Date());
			sysUserService.insert(sysUser);
			//插入修改后的所有角色
			for(Integer roleId : sysUserDto.getRoles()){
				SysUserRole sysUserRole = new SysUserRole();
				sysUserRole.setRoleId(roleId);
				sysUserRole.setCreateAt(new Date());
				sysUserRole.setUserId(sysUser.getId());
				sysUserRoleService.insert(sysUserRole);
			}
			//将随机密码发送至添加的用户邮箱，调用EmailUtil工具类
			String email = sysUserDto.getEmail();
			String name = sysUserDto.getName();
			String imgUrl = PropertiesUtil.getProperty("config.properties", "domainUrl")+File.separator+"img"+File.separator+"email.jpg";
			String content = EmailUtil.getEmailContent(name, password, imgUrl);
			EmailUtil.sendEmail(email, name, content);
			respBean.setBody("用户创建成功，密码已发送到指定邮箱");
			return respBean;
		}
		
	}

	
	@RequestMapping("/getUser")
	@ResponseBody
	public RespBean<SysUserInfoResult> getUserById(){
		String email = (String)BaseAction.doGetSession("userCode");
		RespBean<SysUserInfoResult> respBean = new RespBean<SysUserInfoResult>();
		SysUserInfoResult sysUserInfoResult = sysUserService.getUserById(email);
		respBean.setBody(sysUserInfoResult);
		return respBean;
	}
	@RequestMapping("/updatePassword")
	@ResponseBody
	public RespBean<String> updatePassword(String oldPassword,String newPassword) throws Exception{
		if(oldPassword==null||oldPassword.isEmpty()){
			throw new UfdmException("原密码不能为空");
		}
		if(newPassword==null||newPassword.isEmpty()){
			throw new UfdmException("新密码不能为空");
		}
		String email = (String)BaseAction.doGetSession("userCode");
		RespBean<String> respBean = new RespBean<String>();
		String password = sysUserService.getPassword(email);
		if(!password.equals(UfdmMd5Util.MD5Encode(oldPassword.trim()))){
			throw new UfdmException("原密码错误");
		}
		sysUserService.modifyPassword(email,UfdmMd5Util.MD5Encode(newPassword.trim()));
		respBean.setBody("密码修改成功");
		return respBean;
	}
	
	@RequestMapping("/haveEmail")
	@ResponseBody
	public RespBean<String> havaEmail(String email,Long id) throws UfdmException{
		RespBean<String> respBean = new RespBean<String>();
		boolean res = sysUserService.haveEmail(email, id);
		if(res){
			throw new UfdmException("邮箱已注册");
		}
		respBean.setBody("邮箱未注册");
		return respBean;
	}
	
}
